package com.mrli.cat.weather.view;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.RemoteViews;

import com.mrli.cat.weather.R;
import com.mrli.cat.weather.activity.MainActivity;
import com.mrli.cat.weather.service.WakeUpService;
import com.mrli.cat.weather.service.WeatherUpdateService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class WeatherAppWidgetProvider extends AppWidgetProvider {
    private PendingIntent mPendingWakeUp = null;
    private PendingIntent mWeatherUpdate = null;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final Intent wakeintent = new Intent(context, WakeUpService.class);
        final Intent weatherintent = new Intent(context, WeatherUpdateService.class);
        if (mPendingWakeUp == null) {
            mPendingWakeUp = PendingIntent.getService(context, 0, wakeintent, PendingIntent.FLAG_CANCEL_CURRENT);
        }
        if (mWeatherUpdate == null) {
            mWeatherUpdate = PendingIntent.getService(context, 0, weatherintent, PendingIntent.FLAG_CANCEL_CURRENT);
        }
        //非精确的重复闹钟
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), AlarmManager.INTERVAL_HOUR, mWeatherUpdate);
        //如果API大于19
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            //精确的闹钟
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), mWeatherUpdate);
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), mPendingWakeUp);
        }else{
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), mWeatherUpdate);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), mPendingWakeUp);
        }
    }
}